import { defineStore } from 'pinia'
import consoleRouter from '@/router/console' // 用户路由
import ownerRouter from '@/router/owner' // 机主路由
import userInfoStore from './userInfo.js'

const useMenuListStore = defineStore('menuList', {
    state: () => ({
        menuList: getMenuList()
    }),
    actions: {
        setMenuList(type) {
            // 切换左侧菜单   console表示用户端  owner表示机主
            this.menuList = getMenuList()
        }
    }
})

/**
 * 根据权限列表筛选异步路由配置
 * @param {Array} routes - 路由配置表
 * @param {Array} perms - 权限列表
 * @returns {Array} - 筛选后的路由配置
 */
function filterAsyncRouter(routes) {
    const res = []
    const isProvider = userInfoStore().userInfo?.userItem?.isProvider   // 获取是否为机主身份 
  
    routes.forEach(route => {
        // 创建临时变量 tmp  可以在后续的操作中不会修改原始的路由对象。
        const tmp = { ...route }

        if (!tmp.hidden) {
            if (tmp.children) {
                // 先对子路由进行深度筛选，确保子路由也符合权限要求
                tmp.children = filterAsyncRouter(tmp.children);
                if (tmp.children.length > 0) {
                    res.push(tmp);
                }
            } else if (!isProvider || (isProvider && tmp.role != 'provider')) {
                res.push(tmp);
            }
        }
    })

    return res
}

const getMenuList = function () {
    const type = getUrlPath()
    let asyncRoutes
    if (type == 'console') {
        asyncRoutes = consoleRouter[0].children.filter(e => !e.hidden)
    } else {
        asyncRoutes = ownerRouter[0].children.filter(e => !e.hidden)
    }

    let accessedRouters
    accessedRouters = filterAsyncRouter(asyncRoutes)
    return accessedRouters
}

// 根据url决定加载左侧菜单
const getUrlPath = function () {
    const path = window.location.pathname
    let str = ''
    const reg = RegExp('owner/')
    if (path.match(reg)) {
        str = 'owner'
    } else {
        str = 'console'
    }
    return str
}

export default useMenuListStore